package com.sptpc.speaker;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

public class WordHolder extends RecyclerView.ViewHolder
        implements View.OnClickListener {

    private Context mContext;
    private Word mWord;

    private ImageView image;
    private TextView chineseTextView;
    private TextView englishTextView;

    public WordHolder(View itemView, Context mContext) {
        super(itemView);
        this.mContext = mContext;

        image = (ImageView)itemView.findViewById(R.id.word_image);
        chineseTextView = (TextView)itemView.findViewById(R.id.chinese_text_view);
        englishTextView = (TextView)itemView.findViewById(R.id.english_text_view);

        itemView.setOnClickListener(this);
    }

    public void bind(final Word word) {
        if(word.getImageId()!=0) {
            image.setImageResource(word.getImageId());
        } else {
            image.setVisibility(View.GONE);
        }

        chineseTextView.setText(word.getChinese());
        englishTextView.setText(word.getEnglish());

        mWord = word;
    }

    // 点击了某个item时调用
    @Override
    public void onClick(View view) {
        if (mContext instanceof NumbersActivity) {
            NumbersActivity activity = (NumbersActivity) mContext;

            activity.releseMediaPlayer();

            // 申请Audio焦点
            int result = activity.audioManager
                    .requestAudioFocus(activity.focusChangeListener,
                            AudioManager.STREAM_MUSIC,
                            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
            // 申请成功，创建mediaPlayer
            if(result == activity.audioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                activity.mediaPlayer = MediaPlayer.create(activity, mWord.getAudioId());

                activity.mediaPlayer.start();
                activity.mediaPlayer.setOnCompletionListener(
                        new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaPlayer) {
                        activity.releseMediaPlayer();
                    }
                });
            }
        }

    }

}
